﻿using System;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;

namespace PmuRegistry.Silverlight.Pages.Manage
{
	public partial class NetworkModels : Page
	{
		PhasorDataServiceClient m_client;
		bool m_inEditMode = false;
		int m_networkModelID = 0;
		ActivityWindow m_activityWindow;

		public NetworkModels()
		{
			InitializeComponent();
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetNetworkModelListCompleted += new EventHandler<GetNetworkModelListCompletedEventArgs>(client_GetNetworkModelListCompleted);
			m_client.SaveNetworkModelCompleted += new EventHandler<SaveNetworkModelCompletedEventArgs>(client_SaveNetworkModelCompleted);
			this.Loaded += new RoutedEventHandler(NetworkModels_Loaded);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			ListBoxNetworkModelList.SelectionChanged += new SelectionChangedEventHandler(ListBoxNetworkModelList_SelectionChanged);
		}

		void ListBoxNetworkModelList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ListBoxNetworkModelList.SelectedIndex >= 0)
			{
				NetworkModel selectedModel = ListBoxNetworkModelList.SelectedItem as NetworkModel;
				GridNetworkModelDetail.DataContext = selectedModel;
				m_inEditMode = true;
				m_networkModelID = selectedModel.ID;
			}			
		}

		void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();
			ClearForm();
		}

		void ButtonSave_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonSaveTransform);
			sb.Begin();

			NetworkModel model = new NetworkModel();
			model.NetworkElementUID = TextBoxNetworkElementUID.Text.CleanText();
			model.LineBusName = TextBoxBusName.Text.CleanText();
			model.RegionalLineBusID = TextBoxRegionalBusID.Text.CleanText();
			model.LocalLineBusID = TextBoxLocalBusID.Text.CleanText();
			model.ExtraLineBusID = TextBoxExtraBusID.Text.CleanText();
            model.NominalKv = TextBoxNominalKv.Text.ToNullableInteger();

			if (m_inEditMode == true && m_networkModelID != 0)
			{
				model.ID = m_networkModelID;
				m_client.SaveNetworkModelAsync(model, false);
			}
			else
				m_client.SaveNetworkModelAsync(model, true);		
		}

        bool IsValid()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(TextBoxNetworkElementUID.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Network Element UID", SystemMessage = "Please provide valid Network Element UID.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxNetworkElementUID.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxBusName.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Line/Bus Name", SystemMessage = "Please provide valid Line/Bus Name.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxBusName.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxRegionalBusID.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Regional Line/Bus ID", SystemMessage = "Please provide valid Regional Line/Bus ID.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxRegionalBusID.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxLocalBusID.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Local Line/Bus ID", SystemMessage = "Please provide valid Local Line/Bus ID.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxLocalBusID.Focus();
                                                });
                sm.Show();
                return isValid;
            }


            return isValid;
        }

		void NetworkModels_Loaded(object sender, RoutedEventArgs e)
		{
			
		}

		void client_SaveNetworkModelCompleted(object sender, SaveNetworkModelCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Network Model Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			m_client.GetNetworkModelListAsync();
		}

		void client_GetNetworkModelListCompleted(object sender, GetNetworkModelListCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxNetworkModelList.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Network Model List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (m_activityWindow != null)
				m_activityWindow.Close();
		}

		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			m_activityWindow = new ActivityWindow("Loading Data... Please Wait...");
			m_activityWindow.Show();
			m_client.GetNetworkModelListAsync();
		}

		void ClearForm()
		{
			GridNetworkModelDetail.DataContext = new NetworkModel();
			ListBoxNetworkModelList.SelectedIndex = -1;
			m_inEditMode = false;
			m_networkModelID = 0;
		}

	}
}
